import React, { Component } from 'react';
import {
  Collapse,
  Form,
  Col,
  Row,
  Input,
  Select,
  DatePicker,
  Upload,
  Modal,
  Icon,
  Button,
} from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import styles from '@/pages/Operate.less';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import router from 'umi/router';
import AntdUpload from '@/components/AntdUpload';
import AntdInput from '@/components/AntdInput';
import SearchSelect from '@/components/SearchSelect';
import AntdFormItem from '@/components/AntdFormItem';
import AdSelect from '@/components/AdSelect';
import AdButton from '@/components/AdButton';
import { codes } from './utils';
import { queryFileList, filterAddFile, filterDeteteFile, queryDict } from '@/utils/common';
import FileReader from '@/components/FileReader';
import { columns1 } from '@/pages/Common/common';
import { allDictList } from '@/utils/constans';

const dateFormat = 'YYYY-MM-DD';
const { RangePicker } = DatePicker;
const Panel = Collapse.Panel;
const { TextArea } = Input;
const { Option } = Select;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 12 },
    lg: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
    lg: { span: 16 },
  },
};

@connect(({ verification, loading, common, component, list }) => ({
  verification,
  list,
  loading: loading.models.verification,
  dictObject: component.dictObject,
  id: verification.id,
}))
@Form.create()
export default class VerificationOperate extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: ['1'],
      fileList: [],
      // id: 0,
      deleteFileIds: [],
      previewVisible: false,
      ownCompany: '',
      previewImage: '',
      cars: [],
      disabled: false,
    };
    this.paneSize = [1];
    this.fileList = [];
  }

  componentDidMount() {
    const {
      verification: { detail },
      match: { params },
      dispatch,
    } = this.props;

    if (params.id) {
      const id = params.id;
      this.queryFileList(id);
      this.setState({ id });
      if (!detail.id) {
        dispatch({
          type: 'verification/verificationDetail',
          payload: { id },
          callback: data => {
            if (!data) return;
            this.setState({ cars: [{ id: data.vehicleId }] });
            this.setFileList(data.attachments);
          },
        });
      }
      if (detail && detail[id] && detail[id]) {
        this.setState({ cars: [{ id: detail[id].vehicleId }] });
        detail[id].attachments && this.setFileList(detail[id].attachments);
      }
    }
  }
  componentWillMount() {
    const allDict = [allDictList.inspectionType, allDictList.currencyType];
    queryDict({ props: this.props, allDict });
  }

  queryFileList = id => {
    queryFileList({
      props: this.props,
      params: { bizId: id, fileBizType: 'YEARAUDIT_MANA' },
      callback: data => {
        if (!data) return;
        this.fileList = data;
        this.props.form.setFieldsValue({ fileTokens: data });
      },
    });
  };

  setFileList = list => {
    const fileList = list.map(file => {
      const { id, fileUrl } = file;
      return {
        uid: id,
        name: fileUrl.substring(fileUrl.lastIndexOf('\\') + 1, fileUrl.length),
        status: 'done',
        url: `/server/api/tms/tms-attachment/readFile?path=${fileUrl}&token=${localStorage.getItem(
          'token'
        )}`,
        id,
      };
    });
    this.setState({ fileList });
  };

  callback = key => {
    this.setState({
      activeKey: key,
    });
  };

  operatePaneButton = e => {
    e.stopPropagation();
    e.preventDefault();
    const {
      match: { params },
      form,
      dispatch,
    } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        const {
          yearAuditTime,
          nextAnnualTime,
          mdsCompanyId,
          expiryTime,
          fileTokens,
          ...value
        } = values;
        const { fileList, deleteFileIds, cars } = this.state;
        if (yearAuditTime) {
          value.yearAuditTime = moment(yearAuditTime).format(dateFormat);
        }
        if (nextAnnualTime) {
          value.nextAnnualTime = moment(nextAnnualTime).format(dateFormat);
        }
        if (expiryTime) {
          value.expiryStartTime = moment(expiryTime[0]).format(dateFormat);
          value.expiryEndTime = moment(expiryTime[1]).format(dateFormat);
        }
        value.fileTokens = filterAddFile(fileTokens);
        value.deleteFileIds = filterDeteteFile(fileTokens, this.fileList);
        if (cars.length > 0) {
          const vehicleId = cars.map(v => {
            return v.id;
          });
          value.vehicleId = vehicleId.join(',');
        } else {
          value.vehicleId = '';
        }

        //编辑
        if (params.id) {
          value.id = params.id;
          dispatch({
            type: 'verification/verificationOperate',
            payload: value,
            callback: () => {
              this.queryFileList(params.id);
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
              dispatch({
                type: 'verification/verificationList',
                payload: {},
              });
            },
          });

          //新增
        } else {
          dispatch({
            type: 'verification/verificationOperate',
            payload: value,
            callback: res => {
              if (!res) return;
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
              this.queryFileList(res);
              dispatch({
                type: 'verification/verificationDetail',
                payload: { id: res },
                callback: data => {
                  if (!data) return;
                  dispatch({
                    type: 'common/setTabsName',
                    payload: {
                      id: res,
                      name: data.annualNo,
                      isReplaceTab: true,
                    },
                    callback: result => {
                      if (result) {
                        router.push(`/carDaily/verificationList/editVerification/${res}`);
                      }
                    },
                  });
                },
              });
              dispatch({
                type: 'verification/verificationList',
                payload: {},
              });
            },
          });
        }
      }
    });
  };

  // 上传图片
  handleChange = fileList => {
    this.setState({ fileList });
  };

  // 删除图片
  onRemove = deleteFileIds => {
    this.setState({
      deleteFileIds,
    });
  };
  getValue = values => {
    const ownCompany = values.map(v => {
      return v.ownCompanyName;
    });
    this.setState({
      cars: values,
      ownCompany,
    });
  };
  render() {
    const {
      list,
      type,
      form: { getFieldDecorator },
      verification: { detail },
      dictObject,
      match: { params },
    } = this.props;
    const detailId = params.id;

    const { activeKey, disabled, ownCompany, previewVisible, previewImage, fileList } = this.state;
    const commonParams = {
      getFieldDecorator,
    };

    const customPanelStyle = {
      borderRadius: 4,
      marginBottom: 24,
      border: 0,
      overflow: 'hidden',
    };
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );
    const panel = detail[detailId];
    const genExtraBasicInfo = () => (
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <span>{panel ? panel.annualNo : '新增年审'}</span>
        {disabled ? (
          <AdButton
            type="primary"
            onClick={() => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
            }}
            text="编辑"
            code={panel ? codes.edit : codes.add}
          />
        ) : (
          <Button.Group>
            <AdButton
              type="primary"
              onClick={e => this.operatePaneButton(e)}
              text="保存"
              code={panel ? codes.edit : codes.add}
            />
            {panel && (
              <AdButton
                onClick={() => {
                  this.setState(preState => ({
                    disabled: !preState.disabled,
                  }));
                }}
                text="取消"
                code={panel ? codes.edit : codes.add}
              />
            )}
          </Button.Group>
        )}
      </div>
    );

    const prefixSelector = () => (
      <AntdFormItem
        code="currencyType"
        initialValue={panel ? panel.currencyType : 'CNY'}
        {...commonParams}
      >
        <Select style={{ width: 90 }} disabled={disabled}>
          {dictObject[allDictList.currencyType] &&
            dictObject[allDictList.currencyType].map(item => (
              <Option key={item.code}>{item.value}</Option>
            ))}
        </Select>
      </AntdFormItem>
    );

    return (
      <div className={styles.CollapseUpdate}>
        <PageHeaderWrapper title={genExtraBasicInfo()}>
          <Collapse activeKey={activeKey} onChange={key => this.callback(key)} bordered={false}>
            {this.paneSize.map((item, panelId) => {
              return (
                <Panel
                  header={`${panelId === 0 ? '基础信息' : '证件信息'}`}
                  key={`${panelId + 1}`}
                  style={customPanelStyle}
                  // extra={this.extraButton()}
                >
                  <div className={styles.tableListForm}>
                    <Form layout="inline">
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={12} sm={24}>
                          <Form.Item label="单据号">
                            {getFieldDecorator('annualNo', {
                              initialValue: panel ? panel.annualNo : '保存后系统自动生成',
                            })(<Input placeholder="请输入单据号" disabled={true} />)}
                          </Form.Item>
                        </Col>
                        <Col md={12} sm={24}>
                          <Form.Item label="车牌号">
                            {getFieldDecorator('vehicleId', {
                              rules: [{ required: true, message: '' }],
                              initialValue: panel ? panel.vehicleId : undefined,
                            })(
                              <SearchSelect
                                dataUrl="tms/tms-annual-audit/selectVehicle"
                                url="tms/tms-annual-audit/selectVehicleView_s" // selectedData只只有id时需要传url
                                selectedData={this.state.cars} // 选中值
                                multiple={false} // 是否多选
                                showValue="cartPlateOneNo"
                                searchName="cartPlate"
                                columns={columns1} // 表格展示列
                                onChange={this.getValue} // 获取选中值
                                scrollX={480}
                                id="verification_2"
                                disabled={disabled || (panel && panel.vehicleId)}
                              />
                            )}
                          </Form.Item>
                        </Col>
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={12} sm={24}>
                          <Form.Item label="所属公司">
                            {getFieldDecorator('mdsCompanyId', {
                              initialValue: ownCompany ? ownCompany : panel && panel.ownCompanyName,
                            })(<Input placeholder="请输入" disabled={true} />)}
                          </Form.Item>
                        </Col>
                        <Col md={12} sm={24}>
                          <Form.Item label="时间">
                            {getFieldDecorator('yearAuditTime', {
                              rules: [{ required: true, message: '' }],
                              initialValue:
                                panel && panel.yearAuditTime
                                  ? moment(panel.yearAuditTime, dateFormat)
                                  : null,
                            })(<DatePicker style={{ width: '100%' }} disabled={disabled} />)}
                          </Form.Item>
                        </Col>
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={12} sm={24}>
                          <AntdFormItem
                            label="类型"
                            rules={[{ required: true }]}
                            initialValue={panel ? panel.annualAuditType : undefined}
                            code="annualAuditType"
                            {...commonParams}
                          >
                            <AdSelect
                              disabled={disabled}
                              isExist={true}
                              data={dictObject[allDictList.inspectionType]}
                            />
                          </AntdFormItem>
                        </Col>
                        <Col md={12} sm={24}>
                          <Form.Item label="年审人">
                            {getFieldDecorator('yearAuditName', {
                              rules: [{ required: true, message: '' }],
                              initialValue: panel ? panel.yearAuditName : '',
                            })(<Input placeholder="请输入" disabled={disabled} />)}
                          </Form.Item>
                        </Col>
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={12} sm={24}>
                          <AntdFormItem
                            label="费用"
                            code="feeCost"
                            initialValue={panel ? panel.feeCost : ''}
                            rules={[{ required: true }]}
                            {...commonParams}
                          >
                            <AntdInput
                              mode="money"
                              disabled={disabled}
                              addonBefore={prefixSelector()}
                            />
                          </AntdFormItem>
                        </Col>
                        <Col md={12} sm={24}>
                          <Form.Item label="有效期">
                            {getFieldDecorator('expiryTime', {
                              rules: [{ required: true, message: '' }],
                              initialValue: panel
                                ? [
                                    moment(panel.expiryStartTime, dateFormat),
                                    moment(panel.expiryEndTime, dateFormat),
                                  ]
                                : [],
                            })(<RangePicker style={{ width: '100%' }} disabled={disabled} />)}
                          </Form.Item>
                        </Col>
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={12}>
                          <Form.Item label="下次年审时间">
                            {getFieldDecorator('nextAnnualTime', {
                              rules: [{ required: true, message: '' }],
                              initialValue:
                                panel && panel.nextAnnualTime
                                  ? moment(panel.nextAnnualTime, dateFormat)
                                  : null,
                            })(<DatePicker style={{ width: '100%' }} disabled={disabled} />)}
                          </Form.Item>
                        </Col>
                        <Col md={12}>
                          <Form.Item label="证件号码">
                            {getFieldDecorator('cardCode', {
                              initialValue: panel ? panel.cardCode : '',
                            })(<Input placeholder="请输入" disabled={disabled} />)}
                          </Form.Item>
                        </Col>
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={24}>
                          <Form.Item label="备注">
                            {getFieldDecorator('remarks', {
                              initialValue: panel ? panel.remarks : '',
                            })(<TextArea placeholder="请输入" rows={4} disabled={disabled} />)}
                          </Form.Item>
                        </Col>
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={24}>
                          <Form.Item label="附件">
                            {getFieldDecorator('fileTokens')(
                              <FileReader disabled={disabled} urlType="tms" />
                            )}
                          </Form.Item>
                        </Col>
                      </Row>
                    </Form>
                  </div>
                </Panel>
              );
            })}
          </Collapse>
        </PageHeaderWrapper>
      </div>
    );
  }
}
